package users

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/users"
	usersReq "github.com/flipped-aurora/gin-vue-admin/server/model/users/request"
)

type UsersService struct {
}

// CreateUsers 创建Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) CreateUsers(users users.Users) (err error) {
	err = global.GVA_DB.Create(&users).Error
	return err
}

// DeleteUsers 删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) DeleteUsers(users users.Users) (err error) {
	err = global.GVA_DB.Delete(&users).Error
	return err
}

// DeleteUsersByIds 批量删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) DeleteUsersByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]users.Users{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateUsers 更新Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) UpdateUsers(users users.Users) (err error) {
	err = global.GVA_DB.Save(&users).Error
	return err
}

// GetUsers 根据id获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) GetUsers(id uint) (users users.Users, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&users).Error
	return
}

// GetUsersInfoList 分页获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) GetUsersInfoList(info usersReq.UsersSearch) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&users.Users{})
	var userss []users.Users
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.Name != "" {
		db = db.Where("name = ?", info.Name)
	}
	if info.Student_id != "" {
		db = db.Where("student_id = ?", info.Student_id)
	}
	if info.Password != "" {
		db = db.Where("password = ?", info.Password)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&userss).Error
	return userss, total, err
}

// GetUsersBySidAndPass 根据学号和密码获取获取Users记录
func (usersService *UsersService) GetUsersBySidAndPass(user users.UsersLoginRequest) (users users.Users, err error) {
	err = global.GVA_DB.Where("student_id = ? and password = ? ", user.StudentId, user.Password).First(&users).Error
	return
}
